package com.na.game.util;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public abstract class TimerTask implements Runnable {

	private Timer depend;
	private long delay, period;
	private boolean running;
	private static final ExecutorService EXECUTOR = Executors.newCachedThreadPool();
	
	protected void schedule(Timer depend, long delay, long period) {
		this.depend = depend;
		this.delay = delay;
		this.period = period;
		running = true;
		EXECUTOR.execute(this);
	}
	
	protected void cancel() {
		running = false;
	}
	
	@Override
	public final void run() {
		if (delay > 0) {
			sleep(delay);
		}
		while (running) {
			execute();
			if (period <= 0) {
				break;
			}
			sleep(period);
		}
		depend.remove(this);
	}
	
	private void sleep(long millis) {
		try {
			Thread.sleep(millis);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	public abstract void execute();
}
